package com.xqb.common.handler;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xqb.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author 2092466583
 */
@Slf4j
@Component
public class AutoFillHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");
        this.strictInsertFill(metaObject, "createTime", Date.class,DateTime.now());
        this.strictInsertFill(metaObject, "updateTime", Date.class,DateTime.now());
        String userName;
        try {
            userName = SecurityUtils.getUsername();
        } catch (Exception e) {
            log.error("获取用户信息失败");
            return;
        }
        log.info("userName:{}", userName);
        this.strictInsertFill(metaObject, "createBy", String.class, userName);
        this.strictInsertFill(metaObject, "updateBy", String.class, userName);
        this.strictInsertFill(metaObject, "insId", Long.class,SecurityUtils.getLoginUser().getUser().getInsId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        String userName;
        try {
            userName = SecurityUtils.getUsername();
        } catch (Exception e) {
            //登录的时候还获取不到用户信息，所以这里先不处理
            log.error("获取用户信息失败");
            return;
        }
        log.info("userName:{}", userName);
        this.strictUpdateFill(metaObject, "updateTime", Date.class,DateTime.now());
        this.strictInsertFill(metaObject, "updateBy", String.class, userName);
    }
}